package com.atguigu.flink0922.chapter05.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/3 10:26
 */
public class Flink03_Sink_ES_Unbounded {
    public static void main(String[] args) {
        
        final ArrayList<HttpHost> hosts = new ArrayList<>();
        hosts.add(new HttpHost("hadoop162", 9200));
        hosts.add(new HttpHost("hadoop163", 9200));
        hosts.add(new HttpHost("hadoop164", 9200));
        
        final ElasticsearchSink.Builder<WaterSensor> esBuilder = new ElasticsearchSink.Builder<>(
            hosts,
            new ElasticsearchSinkFunction<WaterSensor>() {
                @Override
                public void process(WaterSensor element,
                                    RuntimeContext ctx,
                                    RequestIndexer indexer) {
                   
                    // 拿到每个元素, 对元素进行处理(写入到es中)
                    final IndexRequest index = Requests
                        .indexRequest()
                        .index("sensor")
                        .type("_doc")
                        .id(element.getId() + "_" + element.getTs())
                        .source(JSON.toJSONString(element), XContentType.JSON);  // 推荐这种
                    
                    indexer.add(index);
                }
            });
        esBuilder.setBulkFlushMaxActions(1);
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                final String[] split = line.split(",");
                return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
            })
            .addSink(esBuilder.build());
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
